package org.txazo.blog.commons.search;

import java.io.File;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {

	public static void main(String[] args) throws Exception {
		String index = "D:/index";
		String field = "content";

		/** IndexReader */
		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
				index)));

		/** IndexSearcher */
		IndexSearcher searcher = new IndexSearcher(reader);

		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);

		QueryParser parser = new QueryParser(Version.LUCENE_44, field, analyzer);

		Query query = parser.parse("命运");

		TopDocs docs = searcher.search(query, null, 10000);
		ScoreDoc[] scoreDocs = docs.scoreDocs;
		System.out.println(scoreDocs.length);
		for (ScoreDoc doc : scoreDocs) {
			int id = doc.doc;
			Document document = searcher.doc(id);
			System.out.println(document.getField("id"));
			System.out.println(document.getField("name"));
			System.out.println(document.getField("content"));
		}

		reader.close();
	}

}
